
#include <gtest/gtest.h>

#include "nane/lib/nane.h"
#include "nane/FileArchiveSystem/FileArchiveSystem.h"
#include "nane/FileArchiveSystem/FileArchive.h"
#include "nane/core/Manager.h"
#include "nane/core/crt/ModuleManager.h"

#include <string>

typedef nane::Manager<std::string, nane::FileArchiveSystem> FileArchiveManager;

static void s_loadArchiveSystemModule( const nane::ModulePtr& _module )
{
    nane::FileArchiveSystem* fileArchiveSystem = new nane::FileArchiveSystem();
    if( fileArchiveSystem->Initialize(_module) == true )
    {
        FileArchiveManager::AddInterface(fileArchiveSystem->GetFileType(), fileArchiveSystem);
    }
    else
    {
        delete fileArchiveSystem;
    }
}

TEST( NaneTest, FileArchiveSystemCheck )
{
    ASSERT_TRUE( nane::Initialize() );
    nane::ModuleManager::ForeachModule("IFileArchiveSystem", s_loadArchiveSystemModule);
    
    nane::FileArchive fileArchive = FileArchiveManager::Instance("")->CreateArchive("");
    ASSERT_TRUE( fileArchive != nane::NullPtr );
    nane::ReadFilePtr file = fileArchive.OpenFile("test.txt");
    ASSERT_TRUE( file != nane::NullPtr );
    std::string data( "Hello, world!" );
    
    nane::uint32 fileSize = file->Size();
    std::vector<nane::byte> inputData;
    inputData.resize( fileSize + 1, 0 );
    EXPECT_EQ( fileSize, file->Read( &(inputData[0]), fileSize ) );
    EXPECT_STREQ( data.c_str(), reinterpret_cast<const char*>( &(inputData[0]) ) );
    
    //fileArchive->closeFile(file);
    file = nane::NullPtr;
    fileArchive = nane::NullPtr;
    
    std::string zipData("Hello, world!Hello, world!Hello, world!Hello, world!");
    nane::FileArchive zipArchive = FileArchiveManager::Instance("zip")->CreateArchive("ziptest.zip");
    ASSERT_TRUE( zipArchive != nane::NullPtr );
    nane::ReadFilePtr zipFile = zipArchive.OpenFile("ziptest.txt");
    ASSERT_TRUE( zipFile != nane::NullPtr );
    inputData.resize(zipFile->Size() + 1, 0 );
    EXPECT_EQ( zipFile->Size(), zipFile->Read(&(inputData[0]), zipFile->Size()) );
    EXPECT_STREQ( zipData.c_str(), reinterpret_cast<const char*>( &(inputData[0]) ) );
    //zipArchive->closeFile(zipFile);
    zipFile = nane::NullPtr;
    zipArchive = nane::NullPtr;
    
    FileArchiveManager::DestroyAll();
    nane::Shutdown();
}

